<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list" border>
              <el-table-column label="序号" type="index" width="50" />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                small
                layout="prev,pager,next"
                :total="total"
                @current-change="handleCurrentChange"
              />

            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增或者编辑角色 -->
      <!-- 新增弹框 -->
      <el-dialog
        title="新增或者编辑角色"
        :visible.sync="showDialog"
        @closed="resetForm"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog = false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { addRoles, delRoles, getRoles, updateRoles } from '@/api/settings'
export default {
  name: 'VueHrSettings',

  data() {
    return {
      showDialog: false,
      list: [], // 存储所有的角色列表
      pageParams: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      isEdit: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      }
    }
  },

  created() {
    this.loadRoles()
  },

  methods: {
    resetForm() {
      // 重置校验规则和重置数据
      // resetFields 让表单里面的数据回到初始状态
      // 如果一开始表单有数据，回到有数据的状态
      // 如果一开始表单没有数据，就置空
      // 重置校验规则
      this.$refs.roleForm.resetFields()
      // 重置数据
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    hSubmit() {
      // 进行兜底校验
      this.$refs.roleForm.validate((valid) => {
        // 校验失败
        if (!valid) return
        // 校验成功发送请求
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hAdd() {
      this.isEdit = true
      this.showDialog = true
    },
    hEdit(row) {
      console.log(row, 'row')
      // row 是表格的数据对象
      // row对象的引用地址交给 this.roleForm
      // { ...row } 浅拷贝，解决数据表格中数据对象和表单对象指向同一个地址
      this.roleForm = { ... row }
      this.isEdit = true
      this.showDialog = true
    },
    async doEdit() {
      try {
        const res = await updateRoles(this.roleForm)
        console.log(res, 'addRoles')
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 重新获取数据重新渲染页面
        this.showDialog = false
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 进行新增角色
    async doAdd() {
      try {
        const res = await addRoles(this.roleForm)
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 需要计算出最大的页码值 maxPage
        this.total++
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        // 重新赋值改变当前的页码值
        this.pageParams.page = maxPage
        // 重新渲染数据
        this.loadRoles()
        // 关闭弹窗
        this.showDialog = false
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 删除角色
    hDel(id) {
      // console.log(id)
      this.$confirm('您确定要删除此角色嘛?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 发送请求进行删除
        const res = await delRoles(id)
        if (res.code === 10000) {
          this.$message.success('删除成功!')
          // 判断当前页面数据是否只剩下一条
          if (this.list.length === 1) {
            this.pageParams.page--
            if (this.pageParams.page <= 0) {
              this.pageParams.page = 1
            }
          }
          // 重新渲染
          this.loadRoles()
        }
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        // console.log(res)
        if (res.code === 10000) {
          this.$message.success(res.message)
          // 赋值
          this.list = res.data.rows
          this.total = res.data.total
        }
      } catch (error) {
        this.$message.error(error)
      }
    },
    handleCurrentChange(val) {
      this.pageParams.page = val
      // 重新获取数据
      this.loadRoles()
    }
  }
}
</script>

